package com.csw.mybatisSpringboot.controller;

import com.csw.mybatisSpringboot.config.page.PageResult;
import com.csw.mybatisSpringboot.config.quanXian.EscapeUtils;
import com.csw.mybatisSpringboot.config.quanXian.JwtUtil;
import com.csw.mybatisSpringboot.dto.UserListDto;
import com.csw.mybatisSpringboot.dto.UserSaveDto;
import com.csw.mybatisSpringboot.entity.User;
import com.csw.mybatisSpringboot.service.UserService;
import com.csw.mybatisSpringboot.util.SnowFlakeIdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api("用户管理")
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private SnowFlakeIdUtil snowFlakeIdUtil;

    /**
     * http://localhost:8080/swagger-ui.html#/
     *
     * @param userId
     * @return
     */
    @ApiOperation("登录")
    @PostMapping("login")
    public String login(@RequestParam String userId) {

        User user = userService.getById(userId);
        return JwtUtil.createjwt(user);
    }

    @ApiOperation("查询用户列表")
    @PostMapping("list")
    public PageResult<User> list(@RequestBody UserListDto dto) {
        dto.setName(EscapeUtils.escapeSqlSpecialChars(dto.getName()));
        long l = snowFlakeIdUtil.nextId();
        return userService.selectAllByName(dto);
    }

//    @ApiOperation("查询用户列表")
//    @PostMapping("list1")
//    public PageResult<User> list1(@RequestBody UserListDto dto) {
//        dto.setName(EscapeUtils.escapeSqlSpecialChars(dto.getName()));
//        return userService.selectAllByName2(dto);
//    }

    @ApiOperation("新增或者更新用户")
    @PostMapping("addOrUpdate")
    public Boolean addOrUpdate(@RequestBody UserSaveDto dto) {
        userService.addOrUpdate(dto);
        return true;
    }

    @ApiOperation("删除")
    @PostMapping("delete")
    public Boolean delete(@RequestParam String id) {
        User user = userService.getById(id);
        userService.saveOrUpdate(user);
        return true;
    }

    /**
     * 共享锁和排他锁测试
     */
    @ApiOperation("更新")
    @PostMapping("update")
    public void update() {
        userService.updateTest();
    }

    /**
     * 共享锁和排他锁测试
     */
    @ApiOperation("查询")
    @PostMapping("select")
    public void select() {
        userService.selectTest();
    }
}
